var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

var http = require('http');
var async = require('async');

var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/vue";

router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// // localhost:3000/users
// router.get('/', function(req, res) {
//     res.send('用户操作');
// })


// 登录  localhost:3000/users/login
router.get('/login', function(req, res) {
    var username = req.query.username;
    var pwd = req.query.pwd;

    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            console.log(err);
        } else {
            var coll = db.collection('users');
            
            // 如果有这个人存在就直接 登录
            // 否则 的话，要先给这个人注册，之后再登录

            var data = {
                code: 0,
                msg: '登录成功'
            }

            coll.find({name: username}).count(function(err, num) {
                if (num > 0) {
                    // 直接登录
                    coll.find({name: username, pwd: pwd}).count(function(err, num) {
                        if (num > 0) {
                            // console.log('登录');\
                            res.send(data);
                        } else {
                            // console.log('用户名或密码不正确')
                            data.code = -1;
                            data.msg = '用户名或密码不正确';
                            res.send(data);
                        }

                        db.close();
                    })
                } else {
                    // 注册之后登录
                    coll.insertOne({name: username, pwd: pwd}, function(err, result) {
                        if (err) {
                            console.log(err);
                            data.code = -2;
                            data.msg = '注册的时候，失败了';
                            res.send(data);
                        } else {
                            res.send(data);
                        }

                        db.close();
                    })
                }
            })
        }
    })

    // 操作数据库
    // 下载 mongodb 
})


module.exports = router;

